<?php

namespace addons\AppVersions\common\models;

use Yii;
use common\behaviors\MerchantBehavior;
use common\helpers\StringHelper;

/**
 * This is the model class for table "{{%addon_app_versions}}".
 *
 * @property int $id ID
 * @property string $merchant_id 商户id
 * @property string $title 标题
 * @property string $version 新版本号
 * @property string $package_size 包大小
 * @property int $type 类型 1:安卓;2;苹果
 * @property string $content 升级内容
 * @property string $download_url 下载地址
 * @property int $is_enforce 强制更新
 * @property int $status 状态
 * @property string $created_at 创建时间
 * @property string $updated_at 更新时间
 */
class AppVersions extends \common\models\base\BaseModel
{
    use MerchantBehavior;

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%addon_app_versions}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['title', 'version', 'package_size', 'content', 'cate_name'], 'required'],
            [['download_url'], 'required'],
            [['merchant_id' , 'download_num', 'type', 'is_enforce', 'status', 'created_at', 'updated_at'], 'integer'],
            [['version_id'], 'integer', 'min' => 1],
            [['title', 'download_url'], 'string', 'max' => 255],
            [['version', 'package_size'], 'string', 'max' => 30],
            [['content'], 'string', 'max' => 500],
            [['version'], 'processingVersion'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'merchant_id' => '商户id',
            'title' => '标题',
            'version' => '版本号',
            'version_id' => '版本ID',
            'package_size' => '包大小',
            'type' => '类型 1:安卓;2;苹果',
            'cate_name' => '分类标识',
            'content' => '升级内容',
            'download_url' => '下载地址',
            'download_num' => '下载量',
            'is_enforce' => '强制更新',
            'status' => '状态',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCate()
    {
        return $this->hasOne(Cate::class, ['name' => 'cate_name'])->andWhere(['merchant_id' => Yii::$app->services->merchant->getNotNullId()]);
    }

    /**
     * @param $attribute
     */
    public function processingVersion($attribute)
    {
        $version_id = StringHelper::strToInt($this->version);
        if ($version_id === false) {
            $this->addError($attribute, '版本号格式不符');
            return;
        }

        $this->version_id = $version_id;
    }
}